<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">
    <!-- 功能区域 -->
    <div style="margin: 0 0 10px 0;display: flex">
      <el-upload
          style="margin-right: 10px"
          :action="API_BASE_URL+'/disk/upload?isFolder=0&uploaderId=' + userData.userId + '&ParentFolderId=' + data.openFolderId"
          :show-file-list="false"
          :on-success="addFile"
          :on-progress="handleUploadProgress"
          :on-change="handleChange"
      >
        <template slot="uploading">
          <div v-if="data.uploading" class="uploading-animation">
            <!-- 这里放置您的上传动画 -->
            <i class="el-icon-loading"></i>
          </div>
        </template>
        <el-button type="primary">上传文件</el-button>
      </el-upload>

      <el-button type="primary" @click="addFolder">新建文件夹</el-button>

      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
      <!--      <el-input v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（所有字段可查）" style="width: 18%;margin-left: 45%"-->
      <!--                clearable></el-input>-->
      <!--      <el-button @click="Load" type="primary" style="margin-left: 2px">查询</el-button>-->
    </div>

    <div style="padding:0 15px 10px;">
      <span style="cursor: pointer;font-size: 15px;color: #8c99a6" @click="loadAllData">全部文件 </span>
      <span style="cursor: pointer;font-size: 15px;color: #8c99a6" @click="loadFolderData(item.fileId)"
            v-for="item in data.folders" :key="item.fileId">
          <span style="color: #72767b;font-size: 15px" class="iconfont-myicons">&#xe7b9;</span> {{ item.fileName }}
      </span>
    </div>


    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        stripe
        style="width: 98%;
        height: 88%;
        border-radius: 5px;
        margin-left: 1%;
        box-sizing: border-box;
        border: 1px solid #ebeef5;
"
        :fixed-header="true"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" sortable prop="fileId" width="40" label="文件ID"/>
      <el-table-column sortable width="700" label="文件名">
        <template v-slot="scope">
          <!--     @mouseenter="scope.row.showOption = true" @mouseleave="scope.row.showOption=false" 鼠标移入的时候显示开关，移出的时候不显示     -->
          <div style="display: flex" @mouseenter="scope.row.showOption = true" @mouseleave="scope.row.showOption=false">
            <div style="display:flex;cursor: pointer;flex: 1;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">
              <div style="display: flex">

                <!--编辑状态：编辑文件名称或者新建文件夹 -->
                <div v-if="scope.row.unSave" style="margin-left: 5px;display: flex;justify-content: center">
                    <span v-html="getFileIcon(scope.row.fileType)"
                                              style="color: #409EFF; font-size: 25px"
                                              class="iconfont-myicons">
                    </span>
                    <el-input @keyup.enter="saveFolder(scope.row)"
                              v-model="scope.row.fileName"
                              size="small"
                              style="width: 180px;margin-left: 2px">
                    </el-input>
                    <el-button style="margin-left: 10px" type="primary" size="small" @click="saveFolder(scope.row)">确定
                    </el-button>
                    <el-button type="danger" size="small" @click="cancel(scope.row)">取消</el-button>
                </div>


                <!-- 非编辑状态：播放或者预览文件信息 -->
                <div v-else style="display: flex;justify-content: center">
                  <!--  点击可编辑或者预览文件  -->
                    <span v-if="scope.row.fileType !== 'folder'" style="cursor: pointer;" @click="handleFileClick(scope.row)">
                               <span v-html="getFileIcon(scope.row.fileType)" style="color: #409EFF; font-size: 25px" class="iconfont-myicons"></span>
                                  <span style="margin-left: 5px">
                                   <span v-if="scope.row.fileType === 'doc' || scope.row.fileType === 'docx'">
                                               <el-tooltip content="点击编辑文件内容" effect="light" :show-after="300">
                                                 <span>{{ scope.row.fileName }}</span>
                                              </el-tooltip>
                                   </span>
                                    <span v-else>
                                            <el-tooltip content="点击预览文件内容" effect="light" :show-after="300">
                                              <span>{{ scope.row.fileName }}</span>
                                            </el-tooltip>
                                    </span>
                                    </span>
                    </span>
                  <!--  点击打开文件夹  -->
                    <span v-else >
                        <span @click="openFolder(scope.row.fileId)">
                             <span v-html="getFileIcon(scope.row.fileType)" style="color: #409EFF; font-size: 25px" class="iconfont-myicons"></span>
                             <span style="margin-left: 5px">{{ scope.row.fileName }}</span>
                        </span>
                   </span>
                </div>


              </div>
            </div>

            <!--      分享、下载、重命名的图标      -->
            <div style="color: #409EFF;margin-right: 10px;font-size: 21px;"
                 v-if="scope.row.showOption && scope.row.fileId && !scope.row.unSave">
              <el-tooltip content="分享" effect="light" :show-after="300">
                <span @click="share(scope.row)" style="font-size: 22px;margin-right: 5px;cursor: pointer"
                      class="iconfont-myicons">&#xe61e;</span>
              </el-tooltip>
              <el-tooltip content="下载" effect="light" :show-after="300" v-if="scope.row.fileType !== 'folder'">
                <span @click="download(scope.row.filePath)" style="font-size: 22px;margin-right: 5px;cursor: pointer"
                      class="iconfont-myicons">&#xe66c;</span>
              </el-tooltip>
              <el-tooltip content="删除" effect="light" :show-after="300">
                <span @click="logicalDeletion(scope.row.fileId)"
                      style="font-size: 22px;margin-right: 5px;cursor: pointer" class="iconfont-myicons">&#xe680;</span>
              </el-tooltip>
              <el-tooltip content="重命名" effect="light" :show-after="300">
                <span @click="reName(scope.row)" style="font-size: 22px;margin-right: 5px;cursor: pointer"
                      class="iconfont-myicons">&#xe611;</span>
              </el-tooltip>
              <el-tooltip content="复制" effect="light" :show-after="300">
                <span style="font-size: 22px;cursor: pointer" class="iconfont-myicons">&#xe839;</span>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="lastModifiedTime" width="300" label="更新时间"/>
      <el-table-column sortable prop="size" width="150" label="存储大小(kb)"/>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 5px"
    ></el-pagination>
  </div>


  <el-dialog v-model="shareVisible" title="分享" width="500" center>
    <el-form label-width="150px" style="padding-right: 50px" :model="data.form">
      <el-form-item label="分享天数">
        <el-radio-group v-model="data.form.days">
          <el-radio :label="3">3天</el-radio>
          <el-radio :label="7">7天</el-radio>
          <el-radio :label="30">30天</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分享链接" v-if="data.shareLink">
        <div style="display: flex">
          <el-input style="flex: 1" v-model="data.shareLink"></el-input>
          <el-button style="margin-left: 10px" type="primary" @click="copyLink(data.shareLink)">复制</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="shareVisible = false">取消</el-button>
        <el-button type="primary" @click="saveShare">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <div style="height: 8vh;">
  </div>


</template>

<script setup>
import {API_BASE_URL} from '@/config';
import {reactive, ref} from "vue";
import request from "../utils/request.js";
//初始化表格
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import moment from 'moment-timezone'

const token = localStorage.getItem('token');
const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userData = dataString ? JSON.parse(dataString) : null;

//相当于data(){}
const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  DefaultName: "新建文件夹",
  CurrentLayer: -1,
  selectedRows: [],//批量删除fileId数组
  openFolderId: 0,//打开的文件夹的Id
  folders: [],
  form: {},
  shareLink: '',
  uploading: false,
});

const shareVisible = ref(false);

// 对应的文件类型和图标
const iconMap = reactive({
  folder: '&#xeb12;',
  doc: '&#xe63d;',
  jpg: '&#xe639;',
  png: '&#xe641;',
  pdf: '&#xe63a;',
  mp4: '&#xe63e;',
  docx: '&#xe643;',
  // pptx: '&#xe600;',
  // xlsx: '&#xe624;',
  md: '&#xe64c;',
  // jpeg: '&#xe619;',
  zip: '&#xe63c;',
});

// 计算属性，基于文件类型返回相应的图标
const getFileIcon = (fileType) => {
  return iconMap[fileType] || '&#xe644;'; // 如果没有找到匹配的图标，则返代表文件的图标
};

const Load = () => {

  // 在Vue组件内部  访问 http://localhost:5173/myFile?id=1&username=hahaha
  // const route = useRoute();
  // const currentPath = route.path; // 获取当前路由路径
  // const query = route.query; // 获取URL的查询参数
  // const currentUrl = window.location.href;
  // console.log("currentUrl：", currentUrl);//currentUrl： http://localhost:5173/myFile?id=1&username=hahaha
  // console.log("currentPath：", currentPath); //currentPath： /myFile
  // console.log("query：", query); // {id: '1', username: 'hahaha'}

  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/file/findFirstLayerFiles?current=${data.currentPage}&size=${data.pageSize}&UserId=${userData.userId}&OpenFolderId=${data.openFolderId}`)
      .then((response) => {
        console.log("我的文件数据：", response);
        data.tableData = response.data.records;
        data.tableData.forEach(item => {
          item.showOption = false  //初始化的时候加上 分享、删除、下载等图标的显示控制开关
        })
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close(); // 无论请求成功或失败，都关闭加载动画
        getParentFolderNames();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除用户
const handleDelete = (id) => {
  console.log("打印id:", id);
  request.delete("/user/delete/" + id).then((response) => {
    console.log(response);
  });
  handleCurrentChange(1);
};


const addFile = (res) => {
  console.log("打印res:", res);
  if (res.code === 200) {
    ElMessage.success("上传成功")
    data.uploading = false
    Load();
  } else {
    ElMessage.error(res.msg)
    Load();
  }
}


const handleUploadProgress = (event, file, fileList) => {
  // 当开始上传时，设置uploading为true
  data.uploading = true;
}


const handleChange = (file, fileList) => {
  // 如果文件列表为空，说明上传结束，设置uploading为false
  if (fileList.length === 0) {
    data.uploading = false;
  }
}

const addFolder = () => {
  data.tableData.unshift({fileName: '', fileType: 'folder', unSave: true})//unSave 控制输入框是否显示
}

const cancel = (row) => {
  let index = row.$index
  if (row.fileId) {//取消编辑
    Load()//重新加载数据
  } else {//取消新增，删除新增所在行
    data.tableData.splice(index, 1)
  }
}

const saveFolder = (row) => {
  if (row.fileId) {//编辑文件（夹）名称
    row.lastModifiedTime = moment().tz('Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss");
    request.put("/disk/update", row).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.data)
        Load()
      } else {
        ElMessage.error(res.data)
        Load()
      }
    })
  } else {//新增文件夹
    request.post(`/disk/upload?FolderName=${row.fileName}&isFolder=1&uploaderId=${userData.userId}&ParentFolderId=${data.openFolderId}`
    ).then((res) => {
      console.log("打印res:", res);
      if (res.code === 200) {
        ElMessage.success(res.msg)
        Load();
      } else {
        ElMessage.error(res.msg)
        Load();
      }
    })
  }
}

const reName = (row) => {
  row.unSave = true
}

//单文件逻辑删除
const logicalDeletion = (fileId) => {
  ElMessageBox.confirm('确定要删除这个文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击了“确定”，在这里执行删除操作
    console.log('用户确认删除，文件ID:', fileId);
    request.delete(`/disk/delete?fileId=${fileId}`).then((res) => {
      console.log("打印res:", res);
      if (res.code === 200) {
        ElMessage.success(res.data)
        Load();
      } else {
        ElMessage.error(res.data)
        Load();
      }
    })
  }).catch(() => {
    // 用户点击了“取消”，不执行操作
    console.log('用户取消删除');
  });
};

//批量逻辑删除
const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.fileId); // 使用 fileId 作为唯一标识
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);
  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定删除选中的文件吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      const res = await request.put('/disk/updateByFileIds', selectedIds);
      console.log('批量删除返回信息：', res);
      // 成功后刷新列表
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
      Load();
    }
  }
};

//文件下载
const download = (filePath) => {
  window.open(filePath);
}

const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const handleFileClick = (row) => {
  // 在此列表中添加所有浏览器可以直接预览的文件类型
  const inlinePreviewTypes = [
    'jpg', 'jpeg', 'png', 'pdf', 'gif', 'bmp', 'svg', 'tiff', 'html', 'txt', 'svg',
    'json', 'js', 'css', 'xml', 'xlsx', 'zip', 'rar', 'mp3', 'mp4', 'java', 'cpp', 'c', 'c#',
    'php', 'go', 'python', 'swift', 'kotlin', 'rust', 'scala', 'ruby', 'perl', 'lua',
    'javascript', 'typescript', 'less', 'scss'
  ];
  // 将文件类型转换为小写以进行不区分大小写的比较
  const fileType = row.fileType.toLowerCase();
  if (inlinePreviewTypes.includes(fileType)) {
    // 网页另外开一个标签页打开  http://localhost:8080/disk/preview/64
    const url = `${API_BASE_URL}/disk/preview/${row.fileId}`;
    // 使用JavaScript的window.open方法在新标签页中打开链接
    window.open(url, '_blank');
  } else {
    let filePath = row.filePath;
    console.log("filePath:" + filePath);
    // 编码您要传递的路径
    const path = encodeURIComponent(filePath);
    // 拼接URL和参数
    const url = `showDoc?filePath=${path}`;
    // 使用JavaScript的window.open方法打开新窗口
    // 第一个参数是要打开的文件路径，第二个参数是窗口名，第三个参数是窗口特性
    // 打开POBrowser窗口，并确保宽度和高度没有'px'后缀
    POBrowser.openWindow(url, '', 'width=1150,height=900');
  }
}


const openFolder = (openFolderId) => {
  console.log("openFolderId:", openFolderId);
  data.openFolderId = openFolderId;
  Load();
}


const getParentFolderNames = () => {
  request.get(`/java/file/findParentFolder?FolderId=${data.openFolderId}`)
      .then((response) => {
        console.log("getParentFolderNames:", response);
        data.folders = response.data;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {

      });
}

//全部文件
const loadAllData = () => {
  data.openFolderId = 0;
  Load();
}

// 加载文件夹 面包屑用
const loadFolderData = (fileId) => {
  data.openFolderId = fileId;
  Load();
}

//分享功能
const share = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//将该行数据（多个字段）存入data.form
  data.form.days = 3  //默认选择3天
  data.form.userId = userData.userId
  data.shareLink = '';
  shareVisible.value = true;
}

const copyLink = (link) => {
  let _input = document.createElement("input");   // 直接构建input
  _input.value = link;  // 设置内容
  document.body.appendChild(_input);    // 添加临时实例
  _input.select();   // 选择实例内容
  document.execCommand("Copy");   // 执行复制
  document.body.removeChild(_input)
  ElMessage.success("复制链接成功")
}


const saveShare = () => {
  if (data.shareLink) {//有了链接，点确定不能再生成了
    shareVisible.value = false
    return;
  }
  console.log("data.form:", data.form);

  const loading = ElLoading.service({
    lock: true,
    text: '分享链接生成中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  request.post(`/disk/share`, data.form).then((res) => {
    console.log(res)
    if (res.code === 200) {
      loading.close()
      ElMessage.success(res.msg)
      let shareData = res.data
      let currentUrl = location.href.substring(0, location.href.indexOf('/myFile'))
      data.shareLink = currentUrl + '/downShare?code=' + shareData.code + '&shareId=' + shareData.id + '&from=' + userData.userId;
    } else {
      loading.close()
      ElMessage.error(res.msg)
    }
  })
}


</script>
